package com.maibow.controller.weixin;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.aliyun.oss.OSSClient;
import com.maibow.constants.OSSConfigurationConstants;
import com.maibow.controller.base.BaseController;
import com.maibow.entity.Page;
import com.maibow.service.organ.OrganService;
import com.maibow.service.system.CommonService;
import com.maibow.service.weixin.WeixinPomotionMsgService;
import com.maibow.util.CommonConstants;
import com.maibow.util.DateUtil;
import com.maibow.util.FileUpload;
import com.maibow.util.PageData;
import com.maibow.util.PathUtil;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.party
 * 文件名：CommercialActivityPublishController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年4月22日-下午8:27:42
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/weixinmsg")
public class WeixinPomotionMsgController extends BaseController {

    @Resource(name = "weixinPomotionMsgService")
    private WeixinPomotionMsgService weixinPomotionMsgService;

    @Resource(name = "commonService")
    private CommonService commonService;

    @Resource(name = "organService")
    private OrganService organService;

    /**
     * 
     * queryWeixinPromotionlistPage(
     * 这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param session
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/list")
    public ModelAndView queryWeixinPromotionlistPage(HttpSession session, Page page) throws Exception {
        logBefore(logger, "推广人列表");
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            if (null != pageData.get("promotion_no") && !"".equals(pageData.get("promotion_no"))) {
                pageData.put("promotion_no", pageData.getString("promotion_no"));
            }

            if (null != pageData.get("promotion_name") && !"".equals(pageData.get("promotion_name"))) {
                pageData.put("promotion_name", pageData.getString("promotion_name"));
            }
            page.setPageData(pageData);
            List<PageData> varList = weixinPomotionMsgService.queryWeixinPromotionlistPage(page);
            modelView.setViewName("system/weixin/weixin_pomotion_msg_list");
            modelView.addObject("varList", varList);
            modelView.addObject("pageData", pageData);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 
     * goViewPromotionMsg(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/goViewPromotionMsg")
    public ModelAndView goViewPromotionMsg(Page page) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        if (null != pageData.get("promotion_id")) {
            String promotion_id = pageData.get("promotion_id").toString();
            pageData.put("promotion_id", Long.valueOf(promotion_id));
        }

        page.setPageData(pageData);
        List<PageData> msgList = weixinPomotionMsgService.queryWeixinPromotionMsglistPage(page);
        modelView.setViewName("system/weixin/weixin_pomotion_msg_view");
        modelView.addObject("varList", msgList);
        modelView.addObject("pageData", pageData);
        return modelView;
    }

    /**
     * 
     * goAddWeixinPomotionMsg(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/goAddWeixinPomotionMsg")
    public ModelAndView goAddWeixinPomotionMsg(Page page) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        modelView.setViewName("system/weixin/weixin_pomotion_msg_add");
        String promotion_id = pageData.getString("promotion_id");
        pageData.put("promotion_id", Long.valueOf(promotion_id));
        modelView.addObject("pageData", pageData);
        return modelView;
    }

    /**
     * 
     * saveWeixinPomotionMsg(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param request
     * 标记：@param promotion_id
     * 标记：@param articles_title
     * 标记：@param content
     * 标记：@param link_url
     * 标记：@param pic_url
     * 标记：@param msg_status
     * 标记：@param msg_type
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/saveWeixinPomotionMsg")
    public ModelAndView saveWeixinPomotionMsg(HttpServletRequest request, @RequestParam(value = "promotion_id", required = false) String promotion_id,
                        @RequestParam(value = "articles_title", required = false) String articles_title, @RequestParam(value = "content", required = false) String content,
                        @RequestParam(value = "link_url", required = false) String link_url, @RequestParam(value = "pic_url", required = false) MultipartFile pic_url,
                        @RequestParam(value = "msg_status", required = false) String msg_status, @RequestParam(value = "msg_type", required = false) String msg_type) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        pageData.put("promotion_id", Long.valueOf(promotion_id));
        if (null != articles_title && !"".equals(articles_title)) {
            pageData.put("articles_title", articles_title);
        }
        if (null != link_url && !"".equals(link_url)) {
            pageData.put("link_url", link_url);
        }

        if (null != pic_url && !pic_url.isEmpty()) {
            String key = processImage(pic_url.getInputStream());
            pageData.put("pic_url", key);
        }

        pageData.put("content", content);
        pageData.put("msg_status", Integer.valueOf(msg_status));
        pageData.put("msg_type", Integer.valueOf(msg_type));

        weixinPomotionMsgService.saveWeixinPromotionMsg(pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 
     * goEditWeixinPomotionMsg(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@return
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/goEditWeixinPomotionMsg")
    public ModelAndView goEditWeixinPomotionMsg() {
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        try {
            pageData.put("msg_id", Integer.valueOf(pageData.get("msg_id").toString()));
            pageData = weixinPomotionMsgService.findWeixinPromotionMsg(pageData);
            modelView.setViewName("system/weixin/weixin_pomotion_msg_edit");
            modelView.addObject("pageData", pageData);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 
     * edit(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param request
     * 标记：@param articles_title
     * 标记：@param content
     * 标记：@param link_url
     * 标记：@param pic_url
     * 标记：@param msg_status
     * 标记：@param msg_type
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/editWeixinPomotionMsg")
    public ModelAndView edit(HttpServletRequest request, @RequestParam(value = "msg_id", required = false) String msg_id,
                        @RequestParam(value = "articles_title", required = false) String articles_title, @RequestParam(value = "content", required = false) String content,
                        @RequestParam(value = "link_url", required = false) String link_url, @RequestParam(value = "pic_url", required = false) MultipartFile pic_url,
                        @RequestParam(value = "msg_status", required = false) String msg_status, @RequestParam(value = "msg_type", required = false) String msg_type,
                        @RequestParam(value = "pic_urlhidden", required = false) String pic_urlhidden) throws Exception {
        ModelAndView modelView = new ModelAndView();
        PageData pageData = this.getPageData();
        pageData.put("msg_id", Integer.valueOf(msg_id));
        if (null != articles_title && !"".equals(articles_title)) {
            pageData.put("articles_title", articles_title);
        }
        if (null != link_url && !"".equals(link_url)) {
            pageData.put("link_url", link_url);
        }

        if (null != pic_url && !pic_url.isEmpty()) {
            String key = processImage(pic_url.getInputStream());
            pageData.put("pic_url", key);
        }

        pageData.put("content", content);
        pageData.put("msg_status", Integer.valueOf(msg_status));
        weixinPomotionMsgService.editWeixinPromotionMsg(pageData);

        modelView.addObject("pageData", pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 
     * processImage(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param inputStream
     * 标记：@return
     * 返回值：String
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    private String processImage(InputStream inputStream) {
        String ffile = DateUtil.getDays(), fileName = "";
        String value = "";

        // 如果是默认图片
        // 如果不是默认图片
        // 先将base64转换成流

        // 上传图片文件名
        String key = this.get32UUID();

        // 再将流转成webp存储到本地
        fileName = PathUtil.getUploadImagePath() + CommonConstants.FILEPATHIMG + ffile + "_profile/" + key + ".png"; // 文件上传路径
        File file = FileUpload.processPng(inputStream, fileName);

        // 再上传到云服务器
        key = "bucket/profile/" + ffile + "/" + key + ".png";
        OSSClient client = new OSSClient(OSSConfigurationConstants.endpoint, OSSConfigurationConstants.accessKeyId, OSSConfigurationConstants.accessKeySecret);
        client.putObject(OSSConfigurationConstants.bucketName, key, file);

        // 删除图片
        file.delete();

        // 先转成webp
        value = key;

        return value;
    }

    @ResponseBody
    @RequestMapping(value = "/deltp/{url1}/{url2}/{url3}/{pic_url}/{msg_id}", method = RequestMethod.POST)
    public ModelAndView deltp(@PathVariable String url1, @PathVariable String url2, @PathVariable String url3, @PathVariable String pic_url, @PathVariable String msg_id, HttpServletRequest request,
                        HttpServletResponse response) {
        logBefore(logger, "删除图片");
        ModelAndView modelView = new ModelAndView();
        String msg = null;
        try {
            PageData pageData = new PageData();
            pageData = this.getPageData();

            pageData.put("msg_id", Integer.valueOf(msg_id));

            // 图片路径
            if (pic_url != null) {
                pic_url = url1 + "/" + url2 + "/" + url3 + "/" + pic_url;
                OSSClient client = new OSSClient(OSSConfigurationConstants.endpoint, OSSConfigurationConstants.accessKeyId, OSSConfigurationConstants.accessKeySecret);
                client.deleteObject(OSSConfigurationConstants.bucketName, pic_url);
                weixinPomotionMsgService.editWeixinPromotionMsgPicUrl(pageData);
            }

            msg = "success";
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

        modelView.addObject(msg);
        return modelView;
    }
}
